package org.leetcode.middle.leetcode49;



import java.util.*;

public class Solution
{



    public List<List<String>> groupAnagrams5(String[] strs){

        Map<String,List<String>> map = new HashMap<>();
        for (String str:strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(str);
            map.put(key,list);
        }
        return new ArrayList<>(map.values());
    }

    public List<List<String>> groupAnagrams2(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();


        for (String str:strs)
        {
            int [] counts = new int[26];
            int length = str.length();

            for (int i = 0; i < length; i++) {
                counts[str.charAt(i)-'a']++;
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < counts.length; i++) {
                if (counts[i]!=0)
                {
                    sb.append((char) 'a'+i);
                    sb.append(counts[i]);
                }
            }

            String key = sb.toString();

            List<String> list = map.getOrDefault(key, new ArrayList<>());

            list.add(str);

            map.put(key,list);
        }

        return new ArrayList<>(map.values());

    }

    /**
     * 错误
     */
    public List<List<String>> groupAnagrams(String[] strs) {

        List<List<String>> res = new ArrayList<>();

        HashMap<Integer, String[]> map = new HashMap<>();

        for (int i = 0; i < strs.length; i++) {
            String[]str = new String[1];
            str[0]=strs[i];
            map.put(i,str);
        }

        for (String [] str:map.values())
        {
            Arrays.sort(str);
        }


        for (int i = 0; i < map.size(); i++) {

            List<String> list = new ArrayList<>();

            list.add(strs[i]);

            for (int j = i+1; j <map.size();j++) {
                if (map.get(j)!=null && map.get(i)==map.get(j))
                {
                    list.add(strs[j]);
                    map.put(j,null);
//                    map.remove(j);
                }
            }

            map.put(i,null);

            res.add(list);
        }

        return res;
    }

    public static void main(String[] args) {
        String [] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
//
//        strs[1]="eat";
//        strs[2]="abc";
//        strs[0]="def";
//
//        String test = "cbd";

//        Arrays.sort(strs);

//        LRUCache solution = new LRUCache();
//        List<List<String>> lists = solution.groupAnagrams(strs);

//        String test2 ="bb";
//
//        int i = test2.charAt(1) - 'a';
//        System.out.println(i);

    }
}
